package com.czxy.tanhua.interceptor;

import com.czxy.tanhua.commons.utils.JwtUtils;
import com.czxy.tanhua.entity.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor extends HandlerInterceptorAdapter {
    /**
     * 处理前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1 获得token
        String token = request.getHeader("Authorization");
        //2 校验token
        boolean verifyToken = JwtUtils.verifyToken(token);
        if(!verifyToken) {
            response.setStatus(401);
            return false;
        }
        //3 获得token中的数据，封装User中
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer)claims.get("id");
        String mobile = (String) claims.get("mobile");
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);

        //4 将user通过工具类，保存threadLocal中
        UserHolder.set(user);
        return true;
    }

    /**
     * 完成后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除
        UserHolder.remove();
    }
}
